package com.huawei.translate.api;

import com.huawei.translate.notification.model.EmailTemplate;
import com.huawei.translate.notification.repository.EmailTemplateRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping("/api/email/")
@Api(value = "email template API", description = "email template api")
public class EmailTemplateApi {

    @Autowired
    private EmailTemplateRepository emailTemplateRepository;

    @ApiOperation(value = "email template", httpMethod = "GET")
    @RequestMapping(value = "/{type}", method = GET)
    public ResponseEntity<String> get(@PathVariable String type) {
        EmailTemplate emailTemplate = emailTemplateRepository.findByTemplateName(type).get(0);
        return new ResponseEntity(emailTemplate.getTemplate(), HttpStatus.OK);
    }

    @ApiOperation(value = "email template", httpMethod = "POST")
    @RequestMapping(value = "/{type}", method = POST)
    public ResponseEntity<String> update(@PathVariable String type, @RequestBody String template) {
        List<EmailTemplate> emailTemplates = emailTemplateRepository.findByTemplateName(type);
        EmailTemplate emailTemplate = new EmailTemplate();
        if (emailTemplates.size() == 0) {
            emailTemplate.setTemplateName(type);
            emailTemplate.setTemplate(template);
        } else {
            emailTemplate = emailTemplates.get(0);
            emailTemplate.setTemplate(template);
        }
        emailTemplateRepository.save(emailTemplate);
        return new ResponseEntity(emailTemplate.getTemplate(), HttpStatus.OK);
    }


}
